#coding=utf-8
'''
Created on 2015年5月28日
'''
from util_base.common_utils import Dict
from common_base.errors import AliveError
from common_base.constants import LanguageType


class ResponseBuilder(object):
    '''
    响应
    '''

    @staticmethod
    def build_error(handler, e):
        '''
        返回错误
        
        Args:
            handler: torndb.web.RequestHandler object
            e: An instance of UFOException
        Returns:
            dict
        '''
        
        res = {}
        res['common'] = {}
        res['common']['code'] = e.code
        language_type = getattr(handler, 'language', LanguageType.CN)
        if e.code == AliveError.ERROR_COMMON_REQUEST_PARAM_INVALID:
            res['common']['message'] = AliveError.get_message(e.code, language_type) + e.message
        else:
            if e.message:
                res['common']['message'] = e.message
            else:
                res['common']['message'] = AliveError.get_message(e.code, language_type)
        res['common']['timestamp'] = handler.timestamp
        res['common']['cmdId'] = handler.cmdid
        res['common']['userId'] = handler.userid
        
        if hasattr(handler, 'alert'):
            res['common']['alert'] = getattr(handler, 'alert')
        
        if e.ext:
            res['data'] = e.ext
        
        return Dict(res)
    
    @staticmethod
    def build_success(handler, data=None):
        '''
        返回成功
        
        Args:
            handler: torndb.web.RequestHandler object
            data: data returned by processor     
        Returns:
            dict
        '''
        
        res = {}
        res['common'] = {}
        res['common']['code'] = AliveError.SUCCESS
        language_type = getattr(handler, 'language', LanguageType.CN)
        res['common']['message'] = AliveError.get_message(res['common']['code'], language_type)
        res['common']['timestamp'] = handler.timestamp
        res['common']['cmdId'] = handler.cmdid
        res['common']['userId'] = handler.userid
        res['common']['userKey'] = handler.user_key

        res['data'] = data if data is not None else {}
        
        return Dict(res)
